package com.digital.library.common.interceptors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

//解决referer问题时添加的类
public class ReferInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(ReferInterceptor.class);

    @Value("${http.referer.ip}")
    private String ipAddress;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String referer = request.getHeader("referer");
        String remoteAddr = request.getRemoteAddr();
        String remoteUser = request.getRemoteUser();
        String remoteHost = request.getRemoteHost();
        int remotePort = request.getRemotePort();


        String host = request.getServerName();
        if (referer == null) {
            return true;
        }
        java.net.URL url = new java.net.URL(referer);
        if (!host.equals(url.getHost())) {
            List<String> allowRfererIpList = Arrays.asList(ipAddress.split(","));
            if (allowRfererIpList.contains(url.getHost())) {
                return true;
            }
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return false;
        }

        return true;
    }
}
